package com.hanxiaozhang.no1classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * 功能描述: <br>
 * 〈自定义类加载器〉
 *
 * @Author:hanxinghua
 * @Date: 2021/12/9
 */
public class No4CustomClassLoader extends ClassLoader {


    public static void main(String[] args) throws Exception {

        ClassLoader customClassLoader = new No4CustomClassLoader();
        Class clazz = customClassLoader.loadClass("com.hanxiaozhang.no1classloader.Hello");
        Class clazz1 = customClassLoader.loadClass("com.hanxiaozhang.no1classloader.Hello");

        System.out.println(clazz == clazz1);

        Hello hello = (Hello) clazz.newInstance();
        hello.m();

        System.out.println("自定义加载器类的加载器: " + customClassLoader.getClass().getClassLoader());
        System.out.println("自定义加载器的父加载器: " + customClassLoader.getParent());

        System.out.println("系统的加载器: " + getSystemClassLoader());
    }


    /**
     * 重写findClass
     *
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        File file = new File("E:/ITSoftware/IdeaProjects_2018/springboot_demo/springboot-jvm/target/classes/", name.replace(".", "/").concat(".class"));
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int b = 0;

            while ((b = fis.read()) != 0) {
                baos.write(b);
            }

            byte[] bytes = baos.toByteArray();
            baos.close();
            fis.close();

            // 将字节数组转换成Class对象，它在堆内存
            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // throws ClassNotFoundException
        return super.findClass(name);
    }

}
